package com.wanqing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wanqing.constant.MessageConstant;
import com.wanqing.constant.StatusConstant;
import com.wanqing.dto.BookDTO;
import com.wanqing.dto.BookPageQueryDTO;
import com.wanqing.dto.GoodsSalesDTO;
import com.wanqing.entity.Book;
import com.wanqing.exception.DeletionNotAllowedException;
import com.wanqing.mapper.BookMapper;
import com.wanqing.mapper.OrderMapper;
import com.wanqing.result.PageResult;
import com.wanqing.service.BookService;
import com.wanqing.vo.BookVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 图书服务实现类
 */
@Service
@Slf4j
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper bookMapper;
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 保存图书信息
     *
     * @param bookDTO 图书传输对象，包含图书基本信息
     */
    @Override
    @Transactional
    public void save(BookDTO bookDTO) {
        Book book = new Book();
        BeanUtils.copyProperties(bookDTO, book);
        log.info("book:{}", book);
        bookMapper.save(book);
    }

    /**
     * 分页查询图书信息
     *
     * @param bookPageQueryDTO 分页查询传输对象，包含页码和页面大小等信息
     * @return 返回分页结果对象，包含总记录数和当前页数据列表
     */
    @Override
    public PageResult pageQuery(BookPageQueryDTO bookPageQueryDTO, boolean isPaged) {
        // 开始分页
        if (isPaged) {
            PageHelper.startPage(bookPageQueryDTO.getPage(), bookPageQueryDTO.getPageSize());
        }
        Page<BookVO> page = bookMapper.pageQuery(bookPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除图书
     *
     * @param ids 要删除的图书ID列表
     */
    @Override
    public void deleteBatch(List<Long> ids) {
        for (Long id : ids) {
            Book book = bookMapper.getById(id);
            if (book.getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.BOOKLIST_ON_SALE);
            }
            if (bookMapper.countByBookListId(id) > 0) {
                throw new DeletionNotAllowedException(MessageConstant.BOOK_BE_RELATED_BY_BOOKLIST);
            }
        }
        bookMapper.deleteBatch(ids);
    }

    /**
     * 根据ID查询图书信息
     *
     * @param id 图书ID
     * @return 返回图书VO对象，包含图书基本信息
     */
    @Override
    public BookVO getById(Long id) {
        BookVO bookVO = new BookVO();
        Book book = bookMapper.getById(id);
        BeanUtils.copyProperties(book, bookVO);
        return bookVO;
    }

    /**
     * 更新图书信息
     *
     * @param bookDTO 图书传输对象，包含要更新的图书基本信息
     */
    @Override
    public void update(BookDTO bookDTO) {
        Book book = new Book();
        BeanUtils.copyProperties(bookDTO, book);
        bookMapper.update(book);
        List<Long> bookId = Collections.singletonList(bookDTO.getId());
    }

    /**
     * 更新图书状态
     *
     * @param status 图书状态，如启用或禁用
     * @param id     图书ID
     */
    @Override
    public void updateStatus(Integer status, Long id) {
        Book book = Book.builder().status(status).id(id).build();
        bookMapper.update(book);
    }

    /**
     * 根据类别ID获取图书列表
     * <p>
     * 此方法通过调用bookMapper接口的getByCategoryId方法来获取属于特定类别的所有图书
     * 主要用于按类别筛选图书，以便用户可以根据不同的类别浏览图书
     *
     * @param categoryId 类别ID，用于指定需要获取图书的类别
     * @return 返回一个Book对象列表，包含指定类别下的所有图书
     */
    @Override
    public List<Book> getByCategoryId(Long categoryId) {
        return bookMapper.getByCategoryId(categoryId);
    }

    /**
     * 条件查询图书
     *
     * @param book
     * @return
     */
    public List<BookVO> list(Book book) {
        List<Book> bookList = bookMapper.getByCategoryId(book.getCategoryId());
        return BeanUtil.copyToList(bookList, BookVO.class);
    }

    @Override
    public List<BookVO> bookStockWarning() {
        return bookMapper.bookStockWarning();
    }


    @Override
    @Transactional
    public List<Book> bookDisabled(LocalDate begin, LocalDate end) {
        ArrayList<Book> bookList = new ArrayList<>();
        if (begin != null && end != null) {
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
            //查询倒三的图书和销量
            List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesPenultimate5(beginTime, endTime);
            //下架倒三的图书
            for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {
                Book book = bookMapper.getByName(goodsSalesDTO.getName());
                bookList.add(book);
                updateStatus(StatusConstant.DISABLE, book.getId());
            }
        }
        //下架缺货的图书
        List<Book> outOfStockBooks = bookMapper.getOutOfStockBooks();
        for (Book book : outOfStockBooks) {
            bookList.add(book);
            updateStatus(StatusConstant.DISABLE, book.getId());
        }
        return bookList;
    }

    @Override
    public Book getBook(BookDTO bookDTO) {
        return bookMapper.getByName(bookDTO.getName());
    }
}
